// Package crons
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2023 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
package crons

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/entity"
	"hotgo/internal/model/input/sysin"
	"hotgo/internal/service"
	"hotgo/utility/client"
	"hotgo/utility/tradeDate"
	"io"
	"strings"
	"time"
)

func init() {
	cron.Register(ZTPool)
}

// ZTPool 测试任务（无参数）
var ZTPool = &cZTPool{name: "zt_pool"}
var ztPoolUrls = []string{
	"http://127.0.0.1:8000/api/public/stock_zt_pool_em",
	"http://127.0.0.1:8000/api/public/stock_zt_pool_dtgc_em",
}

type ztPoolResp struct {
	Code                 string  `json:"代码"`
	Name                 string  `json:"名称"`
	ChangePercent        float64 `json:"涨跌幅"`
	LastPrice            float64 `json:"最新价"`
	Turnover             float64 `json:"成交额"`
	CirculatingMarketCap float64 `json:"流通市值"`
	MarketCap            float64 `json:"总市值"`
	TurnoverRate         float64 `json:"换手率"`
	FBzj                 float64 `json:"封板资金"`
	FirstFBTime          string  `json:"首次封板时间"`
	LastFBTime           string  `json:"最后封板时间"`
	ZBCS                 int     `json:"炸板次数"`
	ZtStatistics         string  `json:"涨停统计"`
	LBNumber             int     `json:"连板数"`
	Industry             string  `json:"所属行业"`
}
type cZTPool struct {
	name string
}

func (c *cZTPool) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cZTPool) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	date := tradeDate.GetLatestDay()
	parse, _ := time.Parse(time.DateOnly, date)
	formatDate := gtime.New(parse).Format("Ymd")
	httpClient := client.GetClient()
	var delIn = &sysin.StockZtPoolDeleteInp{
		Date: date,
	}
	service.SysStockZtPool().Delete(ctx, delIn)
	for _, ztPoolUrl := range ztPoolUrls {
		response, err := httpClient.Get(ctx, fmt.Sprintf("%s?date=%s", ztPoolUrl, formatDate))
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute http.Get err:%+v", err)
			continue
		}
		defer response.Body.Close()
		body, err := io.ReadAll(response.Body)
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute io.ReadAll err:%+v", err)
			continue
		}
		var resp []ztPoolResp
		err = json.Unmarshal(body, &resp)
		if err != nil {
			parser.Logger.Warning(ctx, "cron CloseOrder Execute json.Unmarshal err:%+v", err)
			continue
		}
		for _, emResp := range resp {
			gconv.Int64(emResp.FirstFBTime)
			firstTimeParse, _ := time.Parse("150405", emResp.FirstFBTime)
			lastFBTimeParse, _ := time.Parse("150405", emResp.LastFBTime)
			fisrtFbTime := gtime.New(parse.Format(time.DateOnly)+" "+firstTimeParse.Format(time.TimeOnly), time.DateTime)
			lastFbTime := gtime.New(parse.Format(time.DateOnly)+" "+lastFBTimeParse.Format(time.TimeOnly), time.DateTime)
			ZtStatistics := strings.Split(emResp.ZtStatistics, "/")

			ztStatisticsDays := 1
			ztStatisticsNum := 1
			if len(ZtStatistics) == 2 {
				ztStatisticsDays = gconv.Int(ZtStatistics[0])
				ztStatisticsNum = gconv.Int(ZtStatistics[1])
			}
			err := service.SysStockZtPool().Edit(ctx, &sysin.StockZtPoolEditInp{
				StockZtPool: entity.StockZtPool{
					Code:                 emResp.Code,
					Name:                 emResp.Name,
					ChangePercent:        emResp.ChangePercent,
					LastPrice:            emResp.LastPrice,
					Turnover:             emResp.Turnover,
					CirculatingMarketCap: emResp.CirculatingMarketCap,
					MarketCap:            emResp.MarketCap,
					TurnoverRate:         emResp.TurnoverRate,
					Fbzj:                 emResp.FBzj,
					FirstFbTime:          fisrtFbTime,
					LastFbTime:           lastFbTime,
					Zbcs:                 emResp.ZBCS,
					ZtStatisticsDays:     ztStatisticsDays,
					ZtStatisticsNum:      ztStatisticsNum,
					LbNumber:             emResp.LBNumber,
					Industry:             emResp.Industry,
					Date:                 gtime.New(parse).Format("Y-m-d"),
				},
			})
			if err != nil {
				parser.Logger.Warning(ctx, "cron CloseOrder Execute service.SysStockZhASpotEm().Edit err:%+v", err)
				continue
			}
		}
	}
	return
}
